package test;

import java.awt.Color;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

/**
*
* @author 米强
*/
public class NewJFrame extends javax.swing.JFrame {

    private Color color = Color.BLACK;

    private StyledDocument doc = null;

    private JPanel pane = null;

    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
        doc = textPane.getStyledDocument();
        pane = new JPanel();
        pane.add(new JButton("按钮"));
        // 使用层
        this.getLayeredPane().add(pane, JLayeredPane.DRAG_LAYER);
        pane.setBounds(100, 100, 100, 100);
        pane.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jColorChooser1 = new javax.swing.JColorChooser();
        jFileChooser1 = new javax.swing.JFileChooser();
        jScrollPane1 = new javax.swing.JScrollPane();
        textPane = new javax.swing.JTextPane();
        jButton1 = new javax.swing.JButton();
        b = new javax.swing.JCheckBox();
        i = new javax.swing.JCheckBox();
        font = new javax.swing.JComboBox();
        colorButton = new javax.swing.JButton();
        size = new javax.swing.JComboBox();
        text = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        textPane.setEditable(false);
        jScrollPane1.setViewportView(textPane);

        jButton1.setText("发送");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        b.setText("粗体");

        i.setText("斜体");

        font.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "宋体", "黑体", "行楷", "隶书", "华文新魏", "华文彩云" }));

        colorButton.setText("颜色");
        colorButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
        colorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                colorButtonActionPerformed(evt);
            }
        });

        size.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "12", "14", "18", "22", "26", "36" }));

        jButton2.setText("图片");
        jButton2.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(text, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1)
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(b)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(i)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(font, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(size, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(colorButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addGap(50, 50, 50))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(b)
                    .addComponent(i)
                    .addComponent(font, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(size, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(colorButton)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // 样式属性集
        SimpleAttributeSet set = new SimpleAttributeSet();
        if(b.isSelected()){
            StyleConstants.setBold(set, true);
        }
        if(i.isSelected()){
            StyleConstants.setItalic(set, true);
        }
        String f = (String)font.getSelectedItem();
        StyleConstants.setFontFamily(set, f);
        int s = Integer.parseInt((String)size.getSelectedItem());
        StyleConstants.setFontSize(set, s);
        StyleConstants.setForeground(set, this.color);
        String message = text.getText() + "\n";
        try {
            // 在文档中插入文本，并按照制定的样式集设置显示样式，第一个参数：设置插入点；第二个参数：消息内容（String）；第三个参数：样式集
            doc.insertString(doc.getLength(), message, set);
        } catch (BadLocationException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void colorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_colorButtonActionPerformed
        Color color = jColorChooser1.showDialog(this, "请选择字体颜色", Color.BLACK);
        colorButton.setBackground(color);
        this.color = color;
    }//GEN-LAST:event_colorButtonActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int x = jFileChooser1.showOpenDialog(this);
        if(x == 0){
            File file = jFileChooser1.getSelectedFile();
            textPane.setCaretPosition(doc.getLength());
            // 插入图片，注意：此处不使用文档，直接用JTextPane的insertIcon方法
            textPane.insertIcon(new ImageIcon(file.getPath()));
            textPane.setCaretPosition(doc.getLength());
            // 还可以插入所有Swing组件（非重量级容器）
            textPane.insertComponent(new JButton("按钮"));
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox b;
    private javax.swing.JButton colorButton;
    private javax.swing.JComboBox font;
    private javax.swing.JCheckBox i;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JColorChooser jColorChooser1;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox size;
    private javax.swing.JTextField text;
    private javax.swing.JTextPane textPane;
    // End of variables declaration//GEN-END:variables

}